package com.buli.blmall.generator.convert;

import com.buli.blmall.generator.metadata.TableInfo.TableField;
import com.buli.blmall.generator.metadata.TableInfo;
import com.buli.blmall.generator.metadata.MetaTable;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiang.gao
 * @date 2024/12/11 11:53
 */
public class MetaDataConvert {

    public static TableInfo metaDataConvert(MetaTable.Table table) {
        String className = formatClassName(table.getName());
        TableInfo tableInfo = new TableInfo();
        tableInfo.setName(table.getName());
        tableInfo.setComment(table.getRemarks());
        tableInfo.setObjectName(formatObjectName(table.getName()));
        tableInfo.setEntityName(className);
        List<TableField> tableFields = new ArrayList<>();
        List<MetaTable.Column> columnList = table.getColumnList();
        for (MetaTable.Column column : columnList) {
            TableField tableField = tableInfo.new TableField();
            tableField.setName(column.getName());
            tableField.setJavaField(formatFieldName(column.getName()));
            tableField.setJavaType(column.getJavaType());
            tableField.setComment(column.getRemarks());
            tableField.setPrimaryKey(column.isPrimaryKey());
            tableFields.add(tableField);
        }
        tableInfo.setTableFieldList(tableFields);
        return tableInfo;
    }

    public static String formatClassName(String tableName) {
        String[] words = tableName.split("_");
        StringBuilder className = new StringBuilder();
        for (String word : words) {
            className.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1));
        }
        return className.toString();
    }

    public static String formatObjectName(String tableName) {
        String[] words = tableName.split("_");
        StringBuilder className = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            if (i == 0) {
                className.append(words[i]);
            } else {
                className.append(Character.toUpperCase(words[i].charAt(0))).append(words[i].substring(1));
            }
        }
        return className.toString();
    }

    public static String formatFieldName(String columnName) {
        String[] words = columnName.split("_");
        StringBuilder fieldName = new StringBuilder();
        for (int i = 0; i < words.length; i++) {
            fieldName.append(i == 0 ? StringUtils.toRootLowerCase(words[i]) : Character.toUpperCase(words[i].charAt(0)) + words[i].substring(1));
        }
        return fieldName.toString();
    }


}
